package com.wy.w_ui.banner.indicator

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.example.w_library.utils.DisplayUtil
import com.wy.w_ui.R

/**
 * 圆形指示器-kotlin
 * 在有默认参数值的方法中使用@JvmOverloads注解，则Kotlin就会暴露多个重载方法
 */
class CircleIndicator @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr),
    IWIndicator<FrameLayout> {

    companion object {
        const val VWC = ViewGroup.LayoutParams.WRAP_CONTENT
    }

    private val pointNormal: Int = R.drawable.banner_indicator_normal
    private val pointSelected: Int = R.drawable.banner_indicator_selected

    private var pointLeftRightPadding: Int = 0
    private var pointTopBottomPadding: Int = 0

    init {
        pointLeftRightPadding = DisplayUtil.dp2Px(context, 5)
        pointTopBottomPadding = DisplayUtil.dp2Px(context, 15)
    }

    override fun get(): FrameLayout {
        return this
    }

    override fun onInflate(count: Int) {
        removeAllViews()
        if (count <= 0) return

        val groupView : LinearLayout = LinearLayout(context)
        groupView.orientation = LinearLayout.HORIZONTAL

        var imageView : ImageView
        val lpImageView : LinearLayout.LayoutParams = LinearLayout.LayoutParams(VWC, VWC)
        lpImageView.gravity = Gravity.CENTER_VERTICAL
        lpImageView.setMargins(pointLeftRightPadding,pointTopBottomPadding,pointLeftRightPadding,pointTopBottomPadding)

        for (i in 0 until count){
            imageView = ImageView(context)
            imageView.layoutParams = lpImageView
            if (i == 0){
                imageView.setImageResource(pointSelected)
            }else{
                imageView.setImageResource(pointNormal)
            }
            groupView.addView(imageView)
        }

        val lpGroupView : LinearLayout.LayoutParams = LinearLayout.LayoutParams(VWC, VWC)
        lpGroupView.gravity = Gravity.CENTER or Gravity.BOTTOM
        addView(groupView,lpGroupView)

    }

    override fun onPointChange(current: Int, count: Int) {
        val viewGroup : ViewGroup = getChildAt(0) as ViewGroup
        for (i in 0 until viewGroup.childCount){
            val imageView : ImageView = viewGroup.getChildAt(0) as ImageView
            if (current == i){
                imageView.setImageResource(pointSelected)
            }else{
                imageView.setImageResource(pointNormal)
            }
        }
    }

}